<template>
  <!-- 移动端搜索表单 -->
  <div class="search-form">
    <van-search v-model="form.title" placeholder="请输入试卷标题" />

    <van-cell title="交卷时间" is-link @click="showCalendar = true">
      <template #value>
        <span v-if="form.time">{{ formatTimeRange(form.time) }}</span>
        <span v-else>请选择时间范围</span>
      </template>
    </van-cell>

    <van-calendar
      v-model:show="showCalendar"
      type="range"
      @confirm="onCalendarConfirm"
    />

    <div class="search-buttons">
      <van-button type="primary" block @click="confirm">
        <template #icon><img :src="searchIcon" class="button-icon" /></template>
        查询
      </van-button>
      <van-button type="warning" block @click="reset">
        <template #icon><img :src="resetIcon" class="button-icon" /></template>
        重置
      </van-button>
    </div>
  </div>

  <!-- 下拉刷新和上拉加载更多 -->
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <!-- 无数据提示 -->
      <div
        v-if="tableData.length === 0 && !loading && !refreshing"
        class="empty-tip"
      >
        <van-empty description="暂无考试记录" />
      </div>

      <!-- 考卷列表 -->
      <van-card
        v-for="item in tableData"
        :key="item.id"
        :title="item.title"
        class="exam-card"
      >
        <template #desc>
          <div class="exam-info">
            <div>
              <p>题目数量：{{ item.testCount }}</p>
              <p>考试科目：{{ item.subjectName }}</p>
              <p>创建时间：{{ item.createTime?.replace("T", " ") }}</p>
              <p>总计用时：{{ item.usedTime }}</p>
              <p>得分：{{ item.score }}</p>
            </div>
            <van-button
              class="detail-btn"
              size="small"
              type="primary"
              @click="getMyExam(item)"
            >
              查看
            </van-button>
          </div>
        </template>
      </van-card>
    </van-list>
  </van-pull-refresh>
</template>

<script setup>
import resetIcon from "@/assets/reset.png";
import searchIcon from "@/assets/search.png";
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { showToast } from "vant";
import testResultApi from "@/api/questionItem/testResult";
import { formatDate } from "@/utils/date";

const router = useRouter();
const route = useRoute();

// 响应式数据
const form = reactive({
  title: route.query.title || "",
  time: "",
});

const tableData = ref([]);
const currentPage = ref(1);
const pageSize = 10; // 移动端每页加载更多条数据
const total = ref(0);

// 移动端加载状态
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const showCalendar = ref(false);

// 格式化时间范围展示
const formatTimeRange = (timeRange) => {
  if (!timeRange || !Array.isArray(timeRange)) return "";
  return `${timeRange[0].split("T")[0]} 至 ${timeRange[1].split("T")[0]}`;
};

// 日历确认回调
const onCalendarConfirm = (dates) => {
  const [start, end] = dates;
  // 格式化日期，确保符合接口要求的格式
  form.time = [
    formatDate(start, "YYYY-MM-DDTHH:mm"),
    formatDate(end, "YYYY-MM-DDTHH:mm"),
  ];
  showCalendar.value = false;
};

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true;
  currentPage.value = 1;
  finished.value = false;
  tableData.value = [];
  try {
    await list();
    await getTotal();
  } catch (error) {
    showToast("刷新失败");
  } finally {
    refreshing.value = false;
  }
};

// 上拉加载更多
const onLoad = async () => {
  if (refreshing.value) return;

  if (tableData.value.length >= total.value) {
    finished.value = true;
    return;
  }

  loading.value = true;
  currentPage.value += 1;

  try {
    await list(true);
  } catch (error) {
    showToast("加载失败");
    currentPage.value -= 1;
  } finally {
    loading.value = false;
  }
};

// 方法集
const getMyExam = (data) => {
  router.push({
    path: "/test/answer",
    query: {
      questionItemId: data.questionItemId,
      account: data.account,
      title: `试卷回顾：${data.subjectName}`,
    },
  });
};

// 查询列表，append参数决定是否追加数据
const list = async (append = false) => {
  const res = await testResultApi.getList(form, currentPage.value, pageSize);
  if (append) {
    tableData.value = [...tableData.value, ...res.data];
  } else {
    tableData.value = res.data;
  }

  // 如果返回的数据为空，显示已完成加载
  if (tableData.value.length === 0) {
    finished.value = true;
  }
};

const getTotal = async () => {
  const res = await testResultApi.getTotal(form);
  total.value = res.data;

  // 如果总数为0，直接设置完成状态
  if (total.value === 0) {
    finished.value = true;
  }
};

const confirm = async () => {
  currentPage.value = 1;
  tableData.value = [];
  finished.value = false;
  loading.value = true; // 显示加载状态

  try {
    await getTotal();
    await list();
  } catch (error) {
    showToast("查询失败");
  } finally {
    loading.value = false;
  }
};

const reset = () => {
  form.title = "";
  form.time = "";
};

// 生命周期
onMounted(async () => {
  await list();
  await getTotal();
});
</script>

<style scoped>
.search-form {
  margin-bottom: 15px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(100, 101, 102, 0.08);
  overflow: hidden;
}

.search-buttons {
  display: flex;
  padding: 15px;
  gap: 12px;
}

.exam-card {
  margin-bottom: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: transform 0.2s, box-shadow 0.2s;
}

.exam-card:active {
  transform: scale(0.98);
}

.exam-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.exam-info p {
  margin: 6px 0;
  font-size: 14px;
  color: #646566;
  display: flex;
  align-items: center;
}

.exam-info p::before {
  content: "•";
  margin-right: 6px;
  color: var(--van-primary-color);
  font-weight: bold;
}

/* 添加页面背景色 */
:deep(.van-pull-refresh),
:deep(.van-list) {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding: 12px;
}

/* 美化卡片标题 */
:deep(.van-card__title) {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 10px;
}

/* 美化按钮 */
:deep(.van-button--primary) {
  border-radius: 6px;
}

:deep(.van-button--plain) {
  border-radius: 6px;
}

/* 按钮图标样式 */
.button-icon {
  width: 30px;
  height: 30px;
  vertical-align: middle;
  object-fit: contain;
  margin-right: 4px;
}

/* 确保按钮内容垂直居中并防止换行 */
:deep(.van-button__content) {
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  overflow: hidden;
}

/* 调整按钮内边距以容纳图标 */
:deep(.van-button) {
  padding-left: 12px;
  padding-right: 12px;
}

/* 空数据提示样式 */
.empty-tip {
  padding: 40px 0;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.detail-btn {
  background: linear-gradient(to right, #6a98d1, #1677ff) !important;
  opacity: 0.9;
}
</style>
